import { useRef } from 'react';
import { downloadUtils } from '@/utils';
import { DownloadOutlined, ReloadOutlined, SettingOutlined } from '@ant-design/icons';

import { type DeviceItem, deviceManagerListApi, deviceExport } from '@/api/deviceManagerApi';
import { type ProductDetailItem } from '@/api/equipmentProductApi';
import { DeviceCreateTypeList, DeviceListStatus, typeToValueEnum } from '@/constants';
import { TableLocalePresets } from '@/utils/tableUtils';

import type { ActionType, ProColumns } from '@ant-design/pro-components';

const DeviceArchiveTable = (props: { activeItem: ProductDetailItem }) => {
  const { activeItem = {} } = props;
  const _navigate = useNavigate();
  const actionRef = useRef<ActionType>(null);
  const [exportParams, setExportParams] = useState<Record<string, unknown>>({});

  // 列表请求
  const fetchData = async (params: Record<string, unknown>) => {
    console.log('params', params, activeItem);
    const newParams = {
      productCode: activeItem.mqttUserName,
      ...params,
      deviceCode: params.code,
    };
    const res = await deviceManagerListApi(newParams);
    setExportParams(newParams);
    if (res.success) {
      const responseData = res.data;
      return {
        success: res.success,
        data: responseData?.records ?? [],
        total: responseData?.total ?? 0,
      };
    }
    return {
      success: false,
      data: [],
      total: 0,
    };
  };
  const handleExportDevices = async () => {
    // window.$message.info('导出设备功能开发中，敬请期待...');
    try {
      const response = await deviceExport({
        ...exportParams,
      });
      const res = response as Response;

      if (res.status === 200) {
        downloadUtils.downloadFromResponse(res, '设备列表.xlsx');
        window.$message.success('设备列表导出成功');
      } else {
        const resData = downloadUtils.deCodeArrayBuffer(res.blob());
        if (resData && resData.errorCode) {
          window.$message.error(resData.errorMsg || '导出失败');
        } else {
          window.$message.error('导出失败，请稍后重试');
        }
      }
    } catch (error) {
      console.error('导出设备列表失败:', error);
      window.$message.error('导出失败，请稍后重试');
    }
  };

  // 表格列定义
  const columns: ProColumns<DeviceItem>[] = [
    {
      title: '设备code',
      dataIndex: 'code',
      key: 'code',
      width: 140,
    },
    {
      title: '设备状态',
      dataIndex: 'status',
      key: 'status',
      valueEnum: typeToValueEnum(DeviceListStatus),
      width: 140,
    },
    {
      title: '添加时间',
      dataIndex: 'createTime',
      key: 'createTime',
      search: false,
    },
    {
      title: '创建方式',
      dataIndex: 'source',
      key: 'source',
      search: true,
      valueEnum: typeToValueEnum(DeviceCreateTypeList),
    },
    {
      title: '最近在线时间',
      dataIndex: 'latestOnlineTime',
      key: 'latestOnlineTime',
      width: 220,
      search: false,
    },
    {
      title: '操作',
      key: 'action',
      width: 80,
      fixed: 'right',
      search: false,
      render: (_, _record) => (
        <ASpace size="small">
          <AButton
            type="link"
            size="small"
            onClick={() => {
              // if (record.id) {
              //   navigate(`/equipment/product/detail/${record.id}`);
              // }
              window.$message.warning('开发中...');
            }}
          >
            查看
          </AButton>
        </ASpace>
      ),
    },
  ];
  return (
    <div className="w-full">
      <PProTable<DeviceItem>
        className="mh-table"
        actionRef={actionRef}
        columns={columns}
        request={fetchData}
        rowKey="id"
        search={{
          span: 6,
          labelWidth: 'auto',
          defaultCollapsed: false,
        }}
        pagination={{
          defaultPageSize: 10,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `共 ${total} 项数据，当前显示第 ${range[0]}-${range[1]} 项`,
        }}
        scroll={{ x: 1000 }}
        size="small"
        options={{
          density: false,
          reloadIcon: (
            <AButton icon={<ReloadOutlined />} key="reload">
              刷新
            </AButton>
          ),
          setting: {
            draggable: true,
            checkable: true,
            showListItemOption: true,
            settingIcon: <AButton icon={<SettingOutlined />}>设置</AButton>,
            listsHeight: 400,
          },
        }}
        toolBarRender={() => [
          <AButton
            key="download"
            icon={<DownloadOutlined />}
            type="primary"
            onClick={handleExportDevices}
          >
            导出
          </AButton>,
        ]}
        locale={TableLocalePresets.device(actionRef)}
      />
    </div>
  );
};

export default DeviceArchiveTable;
